from django.db import models
from django.core.validators import MinValueValidator
import time


# 生产计划单
class FaKuyouPlan(models.Model):
    # 状态枚举选项
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    # 基础信息
    id = models.AutoField(primary_key=True, verbose_name='ID')
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产计划单号',
        db_index=True  # 创建索引
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间',
        default=int(time.time()) + 7 * 24 * 60 * 60
    )
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )

    # 商品信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 状态与审核
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='生产状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='最后操作人ID'
    )

    # MRP处理
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间戳
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_plan'
        verbose_name = '生产计划'
        verbose_name_plural = '生产计划管理'
        indexes = [
            models.Index(fields=['workshop_id']),
            models.Index(fields=['goods_code']),
            models.Index(fields=['examine_status', 'status']),
        ]
        ordering = ['-purchase_time']  # 默认按单据日期降序

    def __str__(self):
        return f"{self.purchase_code or '新计划'} - {self.goods_name or '未命名产品'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        if not self.createtime:
            self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.number is not None and self.unit_price is not None:
            self.all_money = float(self.number * self.unit_price)

        super().save(*args, **kwargs)

    @property
    def delivery_datetime(self):
        """交货时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.delivery_time) if self.delivery_time else None

    @property
    def examine_datetime(self):
        """审核时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.examine_time) if self.examine_time else None

    @property
    def create_datetime(self):
        """创建时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.createtime) if self.createtime else None

    @property
    def update_datetime(self):
        """更新时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.updatetime) if self.updatetime else None


# 生产计划详情单
class FaKuyouPlanInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    plan_id = models.IntegerField(null=True, blank=True, verbose_name='计划ID')

    # 商品信息
    goods_id = models.IntegerField(null=True, blank=True, verbose_name='商品ID')
    goods_code = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品编号')
    goods_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品名称')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品规格型号')

    # 单位信息
    unit_id = models.IntegerField(null=True, blank=True, verbose_name='单位ID')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='默认单位')

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 其他信息
    remark = models.TextField(null=True, blank=True, verbose_name='备注')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_plan_info'
        verbose_name = '计划详情'
        verbose_name_plural = '计划详情管理'
        indexes = [
            models.Index(fields=['plan_id']),
            models.Index(fields=['goods_id']),  # 原SQL中为goods_id创建的索引
            models.Index(fields=['goods_code']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.goods_code or '无编号'}-{self.goods_name or '未命名商品'}"


# MRP计算
class FaKuyouMrp(models.Model):
    # 状态枚举选项
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    # 基础信息
    id = models.AutoField(primary_key=True, verbose_name='ID')
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='MRP单号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )

    # 商品信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )

    # 状态与审核
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='处理状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间戳
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        default=time.time()
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        default=time.time()
    )

    class Meta:
        db_table = 'fa_kuyou_mrp'
        verbose_name = 'MRP计算'
        verbose_name_plural = 'MRP计算管理'
        indexes = [
            models.Index(fields=['goods_code']),
            models.Index(fields=['examine_status', 'status']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"MRP-{self.purchase_code or '新单据'}"


# MRP计算详情
class FaKuyouMrpInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    plan_id = models.IntegerField(null=True, blank=True, verbose_name='计划ID')

    # 商品信息
    goods_id = models.IntegerField(null=True, blank=True, verbose_name='商品ID')
    goods_code = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品编号')
    goods_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品名称')
    goods_note = models.CharField(max_length=255, null=True, blank=True, verbose_name='商品规格型号')

    # 单位信息
    unit_id = models.IntegerField(null=True, blank=True, verbose_name='单位ID')
    default_unit = models.IntegerField(null=True, blank=True, verbose_name='默认单位')

    # 数量与价格
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='库存数量'
    )
    buy_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='采购缺口数'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 其他信息
    remark = models.TextField(null=True, blank=True, verbose_name='备注')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_mrp_info'
        verbose_name = 'MRP详情'
        verbose_name_plural = 'MRP详情管理'
        indexes = [
            models.Index(fields=['plan_id']),
            models.Index(fields=['goods_id']),  # 原SQL中为goods_id创建的索引
            models.Index(fields=['goods_code']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"MRP-{self.goods_code or '无编号'}-{self.goods_name or '未命名商品'}"

    def save(self, *args, **kwargs):
        # 自动计算采购缺口数（如果库存和需求数量都存在）
        if self.stock is not None and self.number is not None:
            self.buy_number = max(self.number - self.stock, 0)

        super().save(*args, **kwargs)


# 生产单
class FaKuyouProduction(models.Model):
    # 状态枚举选项
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    # 基础信息
    id = models.AutoField(primary_key=True, verbose_name='ID')
    plan_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产计划单号'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据编号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )

    # 生产信息
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )
    work_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产工人ID'
    )

    # 商品信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='计划数量'
    )
    finish_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='完成数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )

    # 状态与审核
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='生产状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 生产时间
    work_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='开工时间'
    )
    finish_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='完工时间'
    )

    # 时间戳
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_production'
        verbose_name = '生产单'
        verbose_name_plural = '生产单管理'
        indexes = [
            models.Index(fields=['workshop_id']),
            models.Index(fields=['goods_code']),
            models.Index(fields=['examine_status', 'status']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"生产单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now
        self.purchase_time = now

        # 自动计算金额
        if self.finish_number is not None and self.unit_price is not None:
            self.all_money = float(self.finish_number * self.unit_price)

        # 自动更新生产状态
        if self.finish_number is not None and self.number is not None:
            if self.finish_number >= self.number:
                self.status = '1'
                if not self.finish_time:
                    self.finish_time = now
            else:
                self.status = '0'

        super().save(*args, **kwargs)

    @property
    def progress_rate(self):
        """计算生产进度"""
        if self.number and self.finish_number:
            return round(float(self.finish_number) / float(self.number) * 100, 2)
        return 0


# 生产详情单
class FaKuyouProductionInfo(models.Model):
    # 类型枚举选项
    TYPE_CHOICES = [
        ('1', '原材料'),
        ('2', '商品')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='物料类型'
    )
    production_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产单ID'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='规格型号'
    )

    # 单位信息
    unit_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='默认单位'
    )

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='计划数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 库存与领用
    stock_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存数量'
    )
    need_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    requisition_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='领用数量'
    )
    use_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='使用数量'
    )
    back_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )

    # 其他信息
    remark = models.TextField(
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_production_info'
        verbose_name = '生产单详情'
        verbose_name_plural = '生产单详情管理'
        indexes = [
            models.Index(fields=['production_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['type']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.get_type_display()}-{self.goods_code or ''}-{self.goods_name or ''}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        super().save(*args, **kwargs)

    @property
    def usage_rate(self):
        """计算使用率"""
        if self.requisition_number and self.requisition_number > 0:
            return round(float(self.use_number) / float(self.requisition_number) * 100, 2)
        return 0

    @property
    def create_datetime(self):
        """创建时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.createtime) if self.createtime else None

    @property
    def update_datetime(self):
        """更新时间转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.updatetime) if self.updatetime else None


# 领料单
class FaKuyouPicking(models.Model):
    # 状态枚举选项
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    # 单据信息
    id = models.AutoField(primary_key=True, verbose_name='ID')
    plan_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产计划单号'
    )
    production_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产单号'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='领料单号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )

    # 生产信息
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )
    work_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产工人ID'
    )

    # 物料信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='物料名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='物料编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='物料单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='领料数量'
    )
    finish_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='实际领用'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )

    # 状态管理
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='领料状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间信息
    work_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='领料时间'
    )
    finish_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='完成时间'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_picking'
        verbose_name = '生产领料单'
        verbose_name_plural = '生产领料管理'
        indexes = [
            models.Index(fields=['plan_code']),
            models.Index(fields=['production_code']),
            models.Index(fields=['goods_code']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"领料单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.finish_number is not None and self.unit_price is not None:
            self.all_money = float(self.finish_number * self.unit_price)

        # 自动更新领料状态
        if self.finish_number is not None and self.number is not None:
            if self.finish_number >= self.number:
                self.status = '1'
                if not self.finish_time:
                    self.finish_time = now
            else:
                self.status = '0'

        super().save(*args, **kwargs)


# 领料详情单
class FaKuyouPickingInfo(models.Model):
    TYPE_CHOICES = [
        ('1', '原材料'),
        ('2', '商品')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='物料类型'
    )
    production_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产单ID'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='规格型号'
    )

    # 单位信息
    unit_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='默认单位'
    )

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='计划数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 库存与领用
    stock_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存总量'
    )
    need_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    requisition_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='领用数量'
    )
    use_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='使用数量'
    )
    back_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='可用库存'
    )

    # 仓库与批次
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch_name = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='批次名称'
    )

    # 有效期管理
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='到期时间'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )

    # 其他信息
    remark = models.TextField(
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_picking_info'
        verbose_name = '领料单详情'
        verbose_name_plural = '领料单详情管理'
        indexes = [
            models.Index(fields=['production_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['batch_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.get_type_display()}-{self.goods_code or ''}-{self.batch_name or ''}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.purchase is not None and self.number is not None:
            self.money = self.purchase * self.number

        # 自动计算到期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        super().save(*args, **kwargs)


# 退料单
class FaKuyouMaterial(models.Model):
    # 单据类型枚举
    CODE_TYPE_CHOICES = [
        ('1', '加工单'),
        ('2', '委外加工单')
    ]
    # 状态枚举
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    code_type = models.CharField(
        max_length=1,
        choices=CODE_TYPE_CHOICES,
        default='1',
        verbose_name='单据类型'
    )

    # 关联单据信息
    chase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='加工单单号'
    )
    plan_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产计划单号'
    )
    production_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产单号'
    )
    picking_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='领料单单号'
    )
    outsourcing_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='委外加工单单号'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='退料单号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )

    # 生产信息
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )
    work_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='工人ID'
    )
    working_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='工序ID'
    )

    # 物料信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='物料名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='物料编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='物料单位'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )
    finish_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='实际退料'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )

    # 状态管理
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='退料状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间信息
    work_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='退料时间'
    )
    finish_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='完成时间'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_material'
        verbose_name = '生产退料单'
        verbose_name_plural = '生产退料管理'
        indexes = [
            models.Index(fields=['chase_code']),
            models.Index(fields=['production_code']),
            models.Index(fields=['picking_code']),
            models.Index(fields=['working_id']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"退料单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.purchase_time = now
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.finish_number is not None and self.unit_price is not None:
            self.all_money = float(self.finish_number * self.unit_price)

        # 自动更新退料状态
        if self.finish_number is not None and self.number is not None:
            if self.finish_number >= self.number:
                self.status = '1'
                if not self.finish_time:
                    self.finish_time = now
            else:
                self.status = '0'

        super().save(*args, **kwargs)


# 退料详情单
class FaKuyouMaterialInfo(models.Model):
    TYPE_CHOICES = [
        ('1', '原材料'),
        ('2', '商品')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='物料类型'
    )
    production_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产单ID'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='规格型号'
    )

    # 单位信息
    unit_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='默认单位'
    )

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 库存与领用
    stock_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存总量'
    )
    need_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    requisition_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='领用数量'
    )
    use_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='使用数量'
    )
    back_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='可用库存'
    )

    # 仓库与批次
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch_name = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='批次名称'
    )

    # 有效期管理
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='到期时间'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )

    # 其他信息
    remark = models.TextField(
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_material_info'
        verbose_name = '退料单详情'
        verbose_name_plural = '退料单详情管理'
        indexes = [
            models.Index(fields=['production_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['batch_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.get_type_display()}-{self.goods_code or ''}-退料数量:{self.number}"

    def save(self, *args, **kwargs):
        # 自动计算金额
        if self.purchase is not None and self.number is not None:
            self.money = self.purchase * self.number

        # 自动计算到期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        super().save(*args, **kwargs)


# 委外加工单
class FaKuyouOutsourcing(models.Model):
    # 状态枚举选项
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')

    # 单据信息
    plan_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产计划单号'
    )
    production_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产单号'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='委外单号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )

    # 生产信息
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )
    work_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产工人ID'
    )
    customers_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='工厂ID'
    )

    # 物料信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='委外数量'
    )
    finish_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='完成数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='加工单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )
    free_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='委外费用'
    )

    # 状态管理
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='委外状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间信息
    work_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='开工时间'
    )
    finish_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='完工时间'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_outsourcing'
        verbose_name = '委外加工单'
        verbose_name_plural = '委外加工管理'
        indexes = [
            models.Index(fields=['plan_code']),
            models.Index(fields=['production_code']),
            models.Index(fields=['customers_id']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"委外单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.purchase_time = now
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.finish_number is not None and self.unit_price is not None:
            self.all_money = float(self.finish_number * self.unit_price) + float(self.free_money)

        # 自动更新委外状态
        if self.finish_number is not None and self.number is not None:
            if self.finish_number >= self.number:
                self.status = '1'
                if not self.finish_time:
                    self.finish_time = now
            else:
                self.status = '0'

        super().save(*args, **kwargs)


# 委外加工详情单
class FaKuyouOutsourcingInfo(models.Model):
    TYPE_CHOICES = [
        ('1', '原材料'),
        ('2', '商品')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='物料类型'
    )
    production_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='委外单ID'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='规格型号'
    )

    # 单位信息
    unit_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='默认单位'
    )

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='计划数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 库存与领用
    stock_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存总量'
    )
    need_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='需求数量'
    )
    requisition_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='领用数量'
    )
    use_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='使用数量'
    )
    back_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='退料数量'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='可用库存'
    )

    # 仓库与批次
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch_name = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='批次名称'
    )

    # 有效期管理
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='到期时间'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )

    # 其他信息
    remark = models.TextField(
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_outsourcing_info'
        verbose_name = '委外加工单详情'
        verbose_name_plural = '委外加工单详情管理'
        indexes = [
            models.Index(fields=['production_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['batch_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.get_type_display()}-{self.goods_code or ''}-{self.batch_name or ''}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.purchase is not None and self.number is not None:
            self.money = self.purchase * self.number

        # 自动计算到期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        super().save(*args, **kwargs)


# 验收单
class FaKuyouAcceptance(models.Model):
    # 枚举选项
    CODE_TYPE_CHOICES = [
        ('1', '加工单'),
        ('2', '委外加工单')
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]
    STATUS_CHOICES = [
        ('0', '未完成'),
        ('1', '已完成')
    ]
    MRP_STATUS_CHOICES = [
        ('0', '未处理'),
        ('1', '已处理')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    code_type = models.CharField(
        max_length=1,
        choices=CODE_TYPE_CHOICES,
        default='1',
        verbose_name='验收类型'
    )

    # 单据关联信息
    chase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='加工单单号'
    )
    production_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='生产单号'
    )
    outsourcing_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='委外加工单单号'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='验收单号',
        db_index=True
    )
    purchase_time = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    delivery_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='交货时间'
    )

    # 生产信息
    workshop_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='车间ID'
    )
    work_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产工人ID'
    )

    # 物料信息
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_code = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='基本单位ID'
    )

    # 数量与金额
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='验收数量'
    )
    finish_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='实际验收'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='单价'
    )
    all_money = models.FloatField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='总金额'
    )

    # 状态管理
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='验收状态'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # MRP状态
    mrp_status = models.CharField(
        max_length=1,
        choices=MRP_STATUS_CHOICES,
        default='0',
        verbose_name='MRP状态'
    )

    # 时间信息
    work_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='开工时间'
    )
    finish_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='完工时间'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_acceptance'
        verbose_name = '验收单'
        verbose_name_plural = '验收单管理'
        indexes = [
            models.Index(fields=['chase_code']),
            models.Index(fields=['production_code']),
            models.Index(fields=['outsourcing_code']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"验收单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now
        self.purchase_time = now

        # 自动计算金额
        if self.finish_number is not None and self.unit_price is not None:
            self.all_money = float(self.finish_number * self.unit_price)

        # 自动更新验收状态
        if self.finish_number is not None and self.number is not None:
            if self.finish_number >= self.number:
                self.status = '1'
                if not self.finish_time:
                    self.finish_time = now
            else:
                self.status = '0'

        super().save(*args, **kwargs)


# 验收详情单
class FaKuyouAcceptanceInfo(models.Model):
    TYPE_CHOICES = [
        ('1', '原材料'),
        ('2', '商品')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='物料类型'
    )
    production_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='验收单ID'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品编号'
    )
    goods_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品名称'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='规格型号'
    )

    # 单位信息
    unit_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单位ID'
    )
    default_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='默认单位'
    )

    # 价格与数量
    purchase = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='进价'
    )
    need_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='生产数量'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='验收数量'
    )
    bad_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='不合格数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )

    # 库存信息
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='可用库存'
    )

    # 仓库与批次
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch_name = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='批次名称'
    )

    # 有效期管理
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='到期时间'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )

    # 其他信息
    remark = models.TextField(
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_acceptance_info'
        verbose_name = '验收单详情'
        verbose_name_plural = '验收单详情管理'
        indexes = [
            models.Index(fields=['production_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['batch_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.get_type_display()}-{self.goods_code or ''}-{self.batch_name or ''}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算金额
        if self.purchase is not None and self.number is not None:
            self.money = self.purchase * self.number

        # 自动计算到期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        # 验证不合格数量
        if self.bad_number is not None and self.number is not None:
            if self.bad_number > self.number:
                raise ValueError("不合格数量不能超过验收数量")

        super().save(*args, **kwargs)
